package cn.vcjf.weapp.api.active.service.impl;

import cn.vcjf.weapp.api.active.controller.GoodsActiveRecordController;
import cn.vcjf.weapp.api.active.entity.GoodsActive;
import cn.vcjf.weapp.api.active.entity.GoodsActiveRecord;
import cn.vcjf.weapp.api.active.entity.UserActive;
import cn.vcjf.weapp.api.active.mapper.GoodsActiveRecordMapper;
import cn.vcjf.weapp.api.active.mapper.UserActiveMapper;
import cn.vcjf.weapp.api.active.service.GoodsActiveRecordService;
import cn.vcjf.weapp.api.active.service.GoodsActiveService;
import cn.vcjf.weapp.api.active.service.UserActiveService;
import cn.vcjf.weapp.api.goods.entity.GoodsGroup;
import cn.vcjf.weapp.api.goods.entity.GoodsOrder;
import cn.vcjf.weapp.api.goods.entity.GoodsOrderItem;
import cn.vcjf.weapp.api.goods.entity.GoodsRefundOrder;
import cn.vcjf.weapp.api.goods.mapper.GoodsOrderItemMapper;
import cn.vcjf.weapp.api.goods.service.GoodsGroupService;
import cn.vcjf.weapp.api.goods.service.GoodsOrderService;
import cn.vcjf.weapp.api.goods.service.GoodsRefundOrderService;
import cn.vcjf.weapp.api.payment.QfWxPayController;
import cn.vcjf.weapp.api.payment.qfwxpay.model.VcQfPayRes;
import cn.vcjf.weapp.api.setting.entity.OrderOptionConfig;
import cn.vcjf.weapp.api.user.service.UserService;
import cn.vcjf.weapp.common.Interceptor.TokenInterceptor;
import cn.vcjf.weapp.common.exception.ServiceException;
import cn.vcjf.weapp.common.util.CacheUtils;
import cn.vcjf.weapp.common.util.DateUtils;
import cn.vcjf.weapp.common.util.ThreadManager;
import cn.vcjf.weapp.common.util.weixin.WechatUtils;
import cn.vcjf.weapp.common.web.TableResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-09-26
 */
@Service("goodsCollageOrderService")
public class GoodsActiveRecordServiceImpl extends ServiceImpl<GoodsActiveRecordMapper, GoodsActiveRecord> implements GoodsActiveRecordService {

	private Logger logger = LogManager.getLogger(GoodsActiveRecordServiceImpl.class);

	@Resource
	private GoodsActiveService goodsActiveService;
	@Resource
	private UserActiveService userActiveService;
	@Resource
	private GoodsOrderService goodsOrderService;
	@Resource
	private GoodsOrderItemMapper goodsOrderItemMapper;
	@Resource
	private GoodsGroupService goodsGroupService;
	@Resource
	private UserActiveMapper userActiveMapper;
	@Resource
	private GoodsRefundOrderService refundOrderService;
	@Resource
	private OrderOptionConfig orderOptionConfig;
	@Resource
	private UserService userService;

	@Transactional(readOnly = false)
	@Override
	public GoodsActiveRecord selectCollageForUpdateById(Integer id) {
		GoodsActiveRecord goodsActiveRecord = baseMapper.selectCollageForUpdateById(id);
		Wrapper<UserActive> query = new EntityWrapper<>();
		query.eq("collageOrderId", id);

		List<UserActive> list = userActiveService.selectList(query);
		goodsActiveRecord.setActiveUserList(list);

		return goodsActiveRecord;
	}
	@Override
	public GoodsActiveRecord selectCollageById(Integer id) {
		GoodsActiveRecord goodsActiveRecord = baseMapper.selectById(id);
		Wrapper<UserActive> query = new EntityWrapper<>();
		query.eq("collageOrderId", id);

		List<UserActive> list = userActiveService.selectList(query);
		goodsActiveRecord.setActiveUserList(list);

		return goodsActiveRecord;
	}
	/**
	 * 发起拼团或砍价(创建活动记录),创建订单
	 *
	 * @param goodsActiveRecord
	 * @param goodsOrder
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@Override
	public TableResult addGoodsCollageOrder(GoodsActiveRecord goodsActiveRecord, GoodsOrder goodsOrder) {

		//获取活动详情
		Integer goodsActiveId = goodsActiveRecord.getGoodsActiveId();
		GoodsActive goodsActive = goodsActiveService.selectById(goodsActiveId);

		//查询库存
		GoodsGroup goodsGroup = goodsGroupService.selectRepertoryForUpdate(goodsActiveRecord.getGoodsGroupId());
		//判断库存是否小于拼团人数
		if (goodsGroup.getGoodsNum() < goodsActive.getCollageNum()) {
			return TableResult.ErrorResult("库存不足!");
		}

		goodsActiveRecord.preInsert();

		Date activeEndTime = goodsActive.getActiveEndTime();
		if (goodsActive.getActiveStarTime().getTime() > System.currentTimeMillis()) {
			return TableResult.ErrorResult("活动时间未开始!");
		}
		if (activeEndTime.getTime() < System.currentTimeMillis()) {
			return TableResult.ErrorResult("活动时间已结束!");
		}
		goodsActiveRecord.setCollageNum(goodsActive.getCollageNum());
		goodsActiveRecord.setCollageNumIn(1);


		//支付回调中修改拼团单的状态
		Date endTime = null;
		//活动类型(1拼团,2砍价)
		if (goodsActive.getActivetype() == 1) {
			endTime = goodsActive.getActiveEndTime();

		} else if (goodsActive.getActivetype() == 2) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MINUTE, goodsActive.getActiveTime());
			endTime = cal.getTime();
		}

		goodsActiveRecord.setActiveEndTime(endTime);
		//活动状态
		goodsActiveRecord.preInsert();

		boolean b = this.insert(goodsActiveRecord);

		//保存用户参与记录
		//砍价记录
		UserActive userActive = new UserActive();
		userActive.setUserId(goodsActiveRecord.getUserId());
		userActive.setCollageOrderId(goodsActiveRecord.getId());
		userActive.setColonel(1);
		//生成砍价的价格

		if (goodsActive.getActivetype() == 2) {
			BigDecimal activePrice = goodsActive.getActivePrice();
			Integer collageNum = goodsActive.getCollageNum();
			BigDecimal divide = activePrice.divide(new BigDecimal(collageNum));
			BigDecimal randomPercent = getRandomPercent(divide);
			userActive.setCutPrice(randomPercent);

			goodsActiveRecord.setCutedPrice(randomPercent);
			//生成活动订单
		} else if (goodsActive.getActivetype() == 1) {

			//		goodsOrder.setBatchOrderNo("BC"+DateUtils.getDate("yyyyMMddHHmmss")+IdGen.randomLong()%1000);
			//生成拼团订单
			goodsOrder.setCollageOrderId(goodsActiveRecord.getId());//活动记录单号

			goodsOrder.setTraMoney(goodsActive.getCostPrice());
			goodsOrder.setTraActualMoney(goodsActive.getActivePrice());
			goodsOrder.setDiscountMoney(null);

			//1,普通,2,拼团,3,砍价,4套餐
			goodsOrder.setOrderType(2);
			//待支付
			goodsOrder.preInsert();
			boolean b1 = goodsOrderService.insert(goodsOrder);
			BigDecimal goodsTotalPrice = new BigDecimal(0);

			//订单商品
			GoodsOrderItem item = new GoodsOrderItem();
			//成交价格
			item.setTradPrice(goodsOrder.getTraMoney());
			item.setOrderNo(goodsOrder.getOrderNo());
			item.setGoodsId(goodsGroup.getGoodsId());
			item.setGroodsGroupId(goodsActive.getGoodsGroupId());
			item.setGoodsNum(1);
			item.preInsert();
			goodsOrderItemMapper.insert(item);

		}

		userActive.preInsert();
		boolean insert = userActiveService.insert(userActive);
		//减少库存
		goodsGroupService.reduceGoodsGroupRepertory(goodsGroup.getId(), 1);

		//拼团
		if (goodsActive.getActivetype() == 1) {
			//TODO 构造下单支付链接
			String params = QfWxPayController.getQfWxPayUrl(goodsOrder);
			//TODO 返回下单支付链接
			return TableResult.DateResult(params);

			//砍价
		} else if (goodsActive.getActivetype() == 2) {

			//返回砍价信息
			return TableResult.OKResult(goodsActiveRecord);
		}
		return TableResult.ErrorResult("未知活动");
	}

	static Random random = new Random();

	/**
	 * 返回给定价格到0之间的随机数
	 *
	 * @param num
	 * @return
	 */
	public static BigDecimal getRandomPercent(BigDecimal num) {
		int nextInt = random.nextInt(100) + 1;
		BigDecimal divide = new BigDecimal(nextInt).divide(new BigDecimal(100)).setScale(2);
		return num.multiply(divide).setScale(2);
	}

	public static void main(String[] args) {
		Random random = new Random();
		int nextInt = random.nextInt(100) + 1;
		System.out.println(nextInt);
	}

	/**
	 * 参与拼团
	 *
	 * @param goodsActiveRecord
	 * @param goodsOrder
	 * @return
	 */
	@Transactional(readOnly = false)
	@Override
	public TableResult doJoinGoodsCoollage(GoodsActiveRecord goodsActiveRecord, GoodsOrder goodsOrder) {
		//查询库存
		GoodsGroup goodsGroup = goodsGroupService.selectRepertoryForUpdate(goodsActiveRecord.getGoodsGroupId());
		//判断库存
		if (goodsGroup.getGoodsNum() <= 0) {
			return TableResult.ErrorResult("库存不足!");
		}

		GoodsActiveRecord goodsCollage = this.selectCollageForUpdateById(goodsActiveRecord.getId());

		Wrapper<GoodsOrder> queryOrder = new EntityWrapper<>();
		queryOrder.eq("collageOrderId", goodsActiveRecord.getId());
		queryOrder.eq("status", GoodsOrder.ORDER_STATUS_OK);
		//查询拼团支付成功的订单
		List<GoodsOrder> goodsOrders = goodsOrderService.selectList(queryOrder);
		if (goodsOrders == null || goodsOrders.size() <= 0) {
			return TableResult.ErrorResult("拼团未发起成功...");
		}
		//goodsOrders.size();

		int collageNumIn = goodsCollage.getCollageNumIn() + 1;
		//需要到支付回调中参与人数加1,
		//参与成功的人数
		goodsCollage.setCollageNumIn(collageNumIn);
		boolean activeFull = false;
		//超过了最大人数
		if (goodsCollage.getCollageNum() < collageNumIn) {
			return TableResult.ErrorResult("人数已满");
			//参与人数齐了
		} else if (goodsCollage.getCollageNum().intValue() == collageNumIn) {
			goodsCollage.setStatus(GoodsActiveRecord.COLLAGE_STATUS_OK);
			activeFull = true;
		}
		//活动人数 > 已参与人数
		goodsCollage.preUpdate();
		if (activeFull) {
			goodsCollage.setCompleteTime(new Date());
		}
		boolean b = this.updateById(goodsCollage);
		//获取活动详情
		GoodsActive goodsActive = goodsActiveService.selectById(goodsCollage.getGoodsActiveId());
		goodsOrder.setCollageOrderId(goodsActiveRecord.getId());
		//活动记录单号

		goodsOrder.setTraMoney(goodsActive.getCostPrice());
		goodsOrder.setTraActualMoney(goodsActive.getActivePrice());
		goodsOrder.setDiscountMoney(null);

		goodsOrder.setGoodNum(1);
		//生成拼团订单
		goodsOrder.preInsert();
		goodsOrder.setStatus(GoodsOrder.ORDER_STATUS_CREATING);
		boolean b1 = goodsOrderService.insert(goodsOrder);

		//保存用户参与记录
		UserActive userActive = new UserActive();
		userActive.setUserId(goodsActiveRecord.getUserId());
		userActive.setCollageOrderId(goodsActiveRecord.getId());
		userActive.preInsert();
		boolean insert = userActiveService.insert(userActive);
		if (!insert) {
			throw new ServiceException("保存用户参与记录失败");
		}
		//TODO 构造支付链接
		String params = QfWxPayController.getQfWxPayUrl(goodsOrder);

		//减少库存
		goodsGroupService.reduceGoodsGroupRepertory(goodsGroup.getId(), 1);
		//超过了最大人数,移除活动锁
		if (activeFull) {
			goodsCollage.setStatus(GoodsActiveRecord.COLLAGE_STATUS_OK);
			this.updateById(goodsCollage);
			/**
			 * 发送拼团成功通知
			 */
			GoodsActiveRecord activeRecord = selectCollageById(goodsCollage.getId());
			String openId = userService.getOpenIdByUserId(goodsCollage.getUserId());
			ThreadManager.getInstance().execute(
					()->sendMinAppTeamMessage(activeRecord, openId, null)
			);
			GoodsActiveRecordController.joinCollageMap.remove(goodsActiveRecord.getId());
		}
		//TODO 返回支付链接
		return TableResult.DateResult(params);
	}

	/**
	 * 取消参与活动
	 *
	 * @param goodsActiveRecord
	 * @return
	 */
	@Override
	@Transactional
	public TableResult cancelGoodsCollage(GoodsActiveRecord goodsActiveRecord) {
		GoodsActiveRecord goodsCollage = this.selectCollageForUpdateById(goodsActiveRecord.getId());
		//取消拼团
		if (goodsCollage.getActivetype() == 1) {
			int i = baseMapper.cancelGoodsCollage(goodsActiveRecord);

			UserActive userActive = new UserActive();
			userActive.setGoodsActiveId(goodsActiveRecord.getGoodsActiveId());
			//修改新团长
			List<UserActive> userActives = userActiveMapper.selectActiveUserList(userActive);
			if (userActives != null && !userActives.isEmpty()) {
				UserActive userActive1 = userActives.get(0);
				GoodsActiveRecord newColonelActiveRecord = new GoodsActiveRecord();
				newColonelActiveRecord.setId(goodsActiveRecord.getId());
				newColonelActiveRecord.setUserId(userActive1.getUserId());
				newColonelActiveRecord.setSysUserId(goodsActiveRecord.getSysUserId());
				baseMapper.updateNewColonel(newColonelActiveRecord);
			}

			//进行退款操作
			GoodsRefundOrder refundOrder = buildActiveRefundOrder(goodsActiveRecord);

			VcQfPayRes vcQfPayRes = refundOrderService.doCancelCollageRefund(refundOrder);

			return TableResult.Result(vcQfPayRes);
			//取消砍价
		} else if (goodsCollage.getActivetype() == 2) {

			int i = baseMapper.cancelCutGoodsPrice(goodsActiveRecord);


			return TableResult.Result(i);
		}
		return TableResult.ErrorResult("未知活动");
	}

	/**
	 * 构建活动的退款订单
	 *
	 * @param goodsActiveRecord
	 * @return
	 */
	@Override
	public GoodsRefundOrder buildActiveRefundOrder(GoodsActiveRecord goodsActiveRecord) {

		GoodsActiveRecord goodsCollage = this.selectById(goodsActiveRecord.getId());
		//获取活动订单
		Wrapper<GoodsOrder> goodOrderQuery = new EntityWrapper<>();
		goodOrderQuery.eq("collageOrderId", goodsCollage.getId());
		GoodsOrder goodsOrder = goodsOrderService.selectOne(goodOrderQuery);

		//订单商品列表
		GoodsOrderItem query = new GoodsOrderItem();
		query.setOrderNo(goodsOrder.getOrderNo());
		List<GoodsOrderItem> goodsOrderItems = goodsOrderItemMapper.selectOrderItemList(query);
		goodsOrder.setOrderItems(goodsOrderItems);

		GoodsRefundOrder refundOrder = new GoodsRefundOrder();
		refundOrder.setReason("用户主动取消[" + goodsCollage.getActiveName() + "]活动");
		refundOrder.setReasonDes("用户主动取消[" + goodsCollage.getActiveDes() + "]活动");
		refundOrder.setRefundMoney(goodsCollage.getActivePrice());
		refundOrder.setGoodsId(goodsCollage.getGoodsGroupId());
		refundOrder.setOrderType(2);
		refundOrder.setUserId(goodsCollage.getUserId());
		refundOrder.setRefundType(3);
		refundOrder.setOrderNo(goodsOrder.getOrderNo());
		//退去全部商品,(活动只有一个商品)
		refundOrder.setOrderItems(goodsOrderItems);

		return refundOrder;
	}

	/**
	 * 参与砍价,只记录参与信息,修改活动详情,不生成订单
	 *
	 * @param goodsActiveRecord
	 * @return
	 */
	@Override
	public TableResult joinBargaining(GoodsActiveRecord goodsActiveRecord) {
		Integer goodsActiveId = goodsActiveRecord.getGoodsActiveId();

		GoodsActiveRecord goodsCollage = this.selectCollageForUpdateById(goodsActiveRecord.getId());

		if (goodsCollage.getStatus() == GoodsActiveRecord.COLLAGE_STATUS_OK) {
			return TableResult.ErrorResult("砍价已结束.");
		}
		GoodsActive goodsActive = goodsActiveService.selectById(goodsActiveId);
		Wrapper<UserActive> query = new EntityWrapper<>();
		query.eq("collageOrderId", goodsActiveRecord.getId());

		List<UserActive> list = userActiveService.selectList(query);

		if (list != null && list.size() >= goodsActive.getCollageNum()) {
			return TableResult.ErrorResult("砍价已结束.");
		}
		BigDecimal cutPrice = new BigDecimal(0);
		if (list != null) {
			for (UserActive userActive : list) {
				cutPrice = cutPrice.add(userActive.getCutPrice());
			}
		}
		//保存用户参与记录
		//砍价记录
		UserActive userActive = new UserActive();
		userActive.setUserId(goodsActiveRecord.getUserId());
		userActive.setCollageOrderId(goodsActiveRecord.getId());
		userActive.setColonel(0);
		//生成砍价的价格
		if (goodsActive.getActivetype() == 2) {
			BigDecimal activePrice = goodsActive.getActivePrice();
			Integer collageNum = goodsActive.getCollageNum();
			BigDecimal divide = activePrice.divide(new BigDecimal(collageNum));
			BigDecimal randomPercent = getRandomPercent(divide);
			userActive.setCutPrice(randomPercent);
			//已砍价格
			goodsActiveRecord.setCutedPrice(cutPrice.add(randomPercent));
		}
		userActive.preInsert();
		boolean insert = userActiveService.insert(userActive);

		int collageNumIn = goodsCollage.getCollageNumIn() + 1;

		String openId = userService.getOpenIdByUserId(goodsCollage.getUserId());

		//参与成功的人数
		goodsCollage.setCollageNumIn(collageNumIn);
		if (goodsActive.getCollageNum() == collageNumIn) {
			goodsCollage.setStatus(GoodsActiveRecord.COLLAGE_STATUS_OK);
			goodsCollage.setCompleteTime(new Date());
			/**
			 * 发送砍价成功通知
			 */
			ThreadManager.getInstance().execute(
					()->sendMinAppCutMessage(goodsCollage, openId, null)
			);
		}
		goodsCollage.preUpdate();
		this.updateById(goodsCollage);


		return TableResult.OKResult(goodsCollage);
	}

	@Override
	public List<GoodsActiveRecord> selectActivePage(Page<GoodsActiveRecord> page, GoodsActiveRecord goodsActiveRecord) {
		return baseMapper.selectActivePage(page, goodsActiveRecord);
	}

	@Scheduled(cron = "0 0 0/1 * * ?")//每小时都执行
	@Override
	public int updateExpireActiveRecord() {

		Integer caet = orderOptionConfig.cut_active_expire_time;
		Integer taet = orderOptionConfig.team_active_expire_time;

		int i1 = baseMapper.updateExpireActiveRecord(1, caet);

		int i = baseMapper.updateExpireActiveRecord(2, taet);

		return i1 + i;
	}

	/**
	 * 发送砍价成功通知
	 * 砍价成功提醒
	 * yXJGDRZ9iD6Wy55n13tQxRXJWcxSx2g9lWYwb096Klg
	 */
	@Override
	public JSONObject sendMinAppCutMessage(GoodsActiveRecord record, String openId, String form_id) {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		JSONObject result;
		if(form_id == null) {
			Queue<String> formIdList = (Queue<String>) CacheUtils.get(TokenInterceptor.FORM_ID+record.getSysUserId());
			if (formIdList == null || formIdList.isEmpty()) {
				result = new JSONObject();
				result.put("code", "0");
				logger.info("推送小程序模板消息失败:没有form_id");
				return result;
			}
			form_id = formIdList.poll();
		}
		logger.info("开始推送小程序模板消息推送:******砍价成功通知******");
		String goodsName = record.getGoodsName();
		String orderMoneySum = record.getCostPrice() + "元";
		String cutedPrice = record.getCutedPrice() + "元";
		List<UserActive> activeUserList = record.getActiveUserList();
		StringBuilder sb = new StringBuilder();
		for (UserActive userActive : activeUserList) {
			sb.append(userActive.getName()+",");
		}
		sb.deleteCharAt(sb.length()-1);
		String cutStatus = "砍价成功";
		String tips = "您可以告知您的好友砍价成功哦！";
		String cutDate =DateUtils.formatDate(record.getCreateTime(),"yyyy/MM/dd HH:mm");
		String basePrice = record.getCostPrice().subtract(record.getCutedPrice()) + "元";
		String [] dataParam = new String[]{
				goodsName,orderMoneySum ,cutedPrice ,sb.toString() ,cutStatus,tips ,cutDate ,basePrice
		};
		JSONObject data = WechatUtils.buildMinAppRequestData(openId,
				"yXJGDRZ9iD6Wy55n13tQxRXJWcxSx2g9lWYwb096Klg",
				"",
				form_id,
				0,
				dataParam);
		logger.info("openId==========={}\ntemplat_idopenId==========={}\n", openId, "yXJGDRZ9iD6Wy55n13tQxRXJWcxSx2g9lWYwb096Klg");
		result = WechatUtils.sendWechatmsgToUser(data);
		logger.info(result.toJSONString());
		return result;
	}
	/**
	 * 发送拼团成功通知
	 * CKGB2nw1L-Mt0UHhE_ikLGKfXp3kVsHcaN_ZbEc6Szk
	 */
	@Override
	public JSONObject sendMinAppTeamMessage(GoodsActiveRecord record, String openId, String form_id) {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		JSONObject result;
		if(form_id == null) {
			Queue<String> formIdList = (Queue<String>) CacheUtils.get(TokenInterceptor.FORM_ID+record.getSysUserId());
			if (formIdList == null || formIdList.isEmpty()) {
				result = new JSONObject();
				result.put("code", "0");
				logger.info("推送小程序模板消息失败:没有form_id");
				return result;
			}
			form_id = formIdList.poll();
		}
		logger.info("开始推送小程序模板消息推送:******拼团成功通知******");
		String goodsName = record.getActiveName();

		List<UserActive> activeUserList = record.getActiveUserList();
		String colonel = "";
		StringBuilder groupMembers = new StringBuilder();
		for (UserActive userActive : activeUserList) {
			if(userActive.getColonel() == 1){
				colonel = userActive.getName();
			}else {
				groupMembers.append(userActive.getName()+",");
			}
		}
		groupMembers.deleteCharAt(groupMembers.length() - 1);
		String activePrice = record.getActivePrice() + "元";
		String teamDate =DateUtils.formatDate(record.getCompleteTime(),"yyyy/MM/dd HH:mm:ss");
		String teamCreateDate =DateUtils.formatDate(record.getCreateTime(),"yyyy/MM/dd HH:mm:ss");
		String teamStatus = "拼团成功";
		String[] dataParam = new String[]{
				goodsName, colonel, teamDate, groupMembers.toString(), activePrice, record.getCollageNum() + "", "1份", teamStatus, teamCreateDate
		};
		JSONObject data = WechatUtils.buildMinAppRequestData(openId,
				"CKGB2nw1L-Mt0UHhE_ikLGKfXp3kVsHcaN_ZbEc6Szk",
				"",
				form_id,
				0,
				dataParam);
		logger.info("openId==========={}\ntemplat_idopenId==========={}\n", openId, "CKGB2nw1L-Mt0UHhE_ikLGKfXp3kVsHcaN_ZbEc6Szk");
		result = WechatUtils.sendWechatmsgToUser(data);
		logger.info(result.toJSONString());
		return result;
	}
	/**
	 * 发送发货通知
	 * 0GXIIK52BaMutvxQCwwEDSr8e82OZ0PGFHJhtt7PfBc
	 */
	@Override
	public JSONObject sendMinAppDeliveryMessage(GoodsOrder order, String form_id) {
		order = goodsOrderService.selectById(order.getId());
		String openId = userService.getOpenIdByUserId(order.getUserId());
		JSONObject result;
		if(form_id == null) {
			Queue<String> formIdList = (Queue<String>) CacheUtils.get(TokenInterceptor.FORM_ID+order.getSysUserId());
			if (formIdList == null || formIdList.isEmpty()) {
				result = new JSONObject();
				result.put("code", "10001");
				result.put("msg", "推送小程序模板消息失败:没有form_id");
				logger.info("推送小程序模板消息失败:没有form_id");
				return result;
			}
			form_id = formIdList.poll();
		}
		logger.info("开始推送小程序模板消息推送:******发货通知******");
		String goodsName = order.getOrderName();
		String expressCompany = order.getExpressCompany();
		String expressNo = order.getExpressNo();
		String deliverTime =DateUtils.formatDate(order.getDeliverTime(),"yyyy年MM月dd日 HH:mm:ss");
		String tips = "请尽快前往个人中心-订单记录确认信息，超过7天将视为自动收货";

		String[] dataParam = new String[]{
				goodsName,expressCompany, expressNo, order.getOrderNo(),tips,deliverTime
		};
		JSONObject data = WechatUtils.buildMinAppRequestData(openId,
				"0GXIIK52BaMutvxQCwwEDSr8e82OZ0PGFHJhtt7PfBc",
				"",
				form_id,
				0,
				dataParam);
		logger.info("openId==========={}\ntemplat_idopenId==========={}\n", openId, "0GXIIK52BaMutvxQCwwEDSr8e82OZ0PGFHJhtt7PfBc");
		result = WechatUtils.sendWechatmsgToUser(data);
		logger.info(result.toJSONString());
		return result;
	}
}
